package com.tanhua.server.service;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentService {

    @Reference
    private CommentApi commentApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private MovementMQService movementMQService;

    //评论列表
    public ResponseEntity<Object> comments(String movementId, Integer page, Integer pagesize) {

        PageResult pageResult = commentApi.queryByMid(movementId,page,pagesize);
        List<Comment> items = (List<Comment>) pageResult.getItems();

        ArrayList<CommentVo> commentVos = new ArrayList<>();

        if(items != null){
            for (Comment item : items) {
                CommentVo vo = new CommentVo();
                BeanUtils.copyProperties(item,vo);

                Long userId = item.getUserId();
                UserInfo userInfo = userInfoApi.findById(userId);
                if(userInfo != null){
                    BeanUtils.copyProperties(userInfo,vo);
                }
                vo.setId(item.getId().toString());
                if(item.getCreated() != null){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
                    vo.setCreateDate(sdf.format(new Date(item.getCreated())));
                }
                vo.setHasLiked(0);
                commentVos.add(vo);
            }
        }
        pageResult.setItems(commentVos);
        return ResponseEntity.ok(pageResult);
    }


    //发布评论业务
    public ResponseEntity<Object> commitComment(String movementId, String comment) {
        Comment c = new Comment();
        c.setPublishId(new ObjectId(movementId));
        c.setCommentType(2);
        c.setPubType(1);
        c.setContent(comment);
        c.setUserId(UserHolder.getUserId());
        c.setCreated(System.currentTimeMillis());

        commentApi.commitComment(c);

        //发送消息，发布评论
        movementMQService.queryPublishMsg(movementId);

        return ResponseEntity.ok(null);
    }
}
